package com.cvte.netservice;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.net.NetworkInfo;


import com.android.internal.policy.cvte.EthernetControl;
import com.mstar.android.tvapi.common.TvManager;
import com.mstar.android.tvapi.common.exception.TvCommonException;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


/**
 * Created by wuguitong on 2016/11/4.
 */
public class NetService extends Service {
    private static final int DELAY_TIME = 30000;
    private WifiManager mWifiManager = null;
    private ConnectivityManager mConnectivityManager = null;
    private Context context = null;
    private EthernetControl sEthernetControl = null;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Boolean isConnect = false;
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                isConnect = mMobileNetworkInfo.isConnected();
                Log.d("wuguitong", "Net is" + isConnect);
            }
            if (sEthernetControl != null) {
                if(!isConnect) {
                    sEthernetControl.setEnabled(false);
                    sEthernetControl.setEnabled(true);
                }
            }
            handler.postDelayed(this,DELAY_TIME);
            try {
                int result = TvManager.getInstance().executeShellCmd("ping -c 3 -w 100 www.baidu.com");
                Log.d("wuguitong", "result is" + result);
            } catch (TvCommonException e) {
                e.printStackTrace();
            }
            CommandResult result = execCommand(new String[]{"ping -c 3 -w 100 www.baidu.com"},true,true);
        }
    };
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("wuguitong", "NetService onCreate");
        context = this;
        if (sEthernetControl == null) {
            sEthernetControl = new EthernetControl();
            sEthernetControl.getSystemService(context);
        }
        handler.postDelayed(runnable,DELAY_TIME);
    }
    public boolean ping() {
        String result = null;
        try {
            TvManager.getInstance().executeShellCmd("su");
            Runtime.getRuntime().exec("su");
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网 
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次 
            // 读取ping的内容，可以不加 
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("wuguitong", "result content : " + stringBuffer.toString());
            // ping的状态 
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } catch (TvCommonException e) {
            e.printStackTrace();
        } finally {
            Log.d("wuguitong", "result = " + result);
        }
        return false;
    }
    public CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? "su" : "sh");
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }

                // donnot use os.writeBytes(commmand), avoid chinese charset error
                os.write(command.getBytes());
                os.writeBytes("\n");
                os.flush();
            }
            os.writeBytes("exit\n");
            os.flush();

            result = process.waitFor();
            // get command result
            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (process != null) {
                process.destroy();
            }
        }
        return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
                : errorMsg.toString());
    }
    public class CommandResult {
    /** result of command **/
        public int    result;
        /** success message of command result **/
        public String successMsg;
        /** error message of command result **/
        public String errorMsg;
        public CommandResult(int result) {
            this.result = result;
        }
        public CommandResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }
    }
}
